package com.hyst.config;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import com.hyst.interceptor.LoginInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.*;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ITemplateResolver;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * @Description:spring mvc 配置类 <a href=
 *                     "http://blog.csdn.net/pinebud55/article/details/53420481">详见配置解析</a>
 *                     <h2>@EnableWebMvc=WebMvcConfigurationSupport,</h2>
 * 
 * @Date：2017年8月9日 @author： DongY
 * @version ：1.0 1.[2017年8月9日]CreatBy：dy
 */
@Configuration
@ComponentScan(basePackages = "com.hyst.web")
@EnableSwagger2
@EnableAspectJAutoProxy // 启用自动代理功能（AOP，相当于XML中配置 <aop:aspectj-autoproxy/>）
public class MvcConfig extends WebMvcConfigurationSupport {
	// @Autowired
	// private Environment env;


	/**
	 * @Description: 配置Jackson消息解析器
	 * @return ViewResolver
	 */
	@Bean
	public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
		final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
		converter.setDefaultCharset(Charset.forName("UTF-8"));
		return converter;
	}

	// @Override
	// @Bean
	// public RequestMappingHandlerAdapter requestMappingHandlerAdapter() {
	// RequestMappingHandlerAdapter adapter = new
	// RequestMappingHandlerAdapter();
	// adapter.setMessageConverters(null);
	// return adapter;
	// }

	@Bean
	public ITemplateResolver templateResolver() {

		final SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
		// 设置是否使用缓存，默认为true
		templateResolver.setCacheable(false);
		templateResolver.setPrefix("/");
//		templateResolver.setPrefix("/thymeleaf/");
		templateResolver.setSuffix(".html");
		templateResolver.setCharacterEncoding("UTF-8");
		templateResolver.setTemplateMode(TemplateMode.HTML);
		return templateResolver;

	}

	@Bean // 生成模板引擎并为模板引擎注入模板解析器
	public TemplateEngine templateEngine(final ITemplateResolver templateResolver) {
		final SpringTemplateEngine templateEngine = new SpringTemplateEngine();
		templateEngine.setTemplateResolver(templateResolver);
		return templateEngine;
	}

	/**
	 * @Description: JSP视图解析器//替换成了thymeleaf的视图解析器了
	 * @return ViewResolver
	 */
	@Bean
	public ViewResolver viewResolver(final TemplateEngine templateEngine) {
		final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
		viewResolver.setContentType("text/html; charset=utf-8");
		viewResolver.setTemplateEngine(templateEngine);
		// InternalResourceViewResolver viewResolver = new
		// InternalResourceViewResolver();
		// viewResolver.setCache(false);
		// viewResolver.setPrefix("/WEB-INF/");
		// viewResolver.setViewClass(JstlView.class);
		// viewResolver.setSuffix(".jsp");
		return viewResolver;
	}

	/**
	 * 将对于静态资源的请求转发到Servlet容器的默认处理静态资源的servlet 因为将spring的拦截模式设置为"/"时会对静态资源进行拦截
	 */
	@Override
	public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer) {
		configurer.enable();
	}

	/**
	 * 添加自定义消息转换器
	 */
	@Override
	public void configureMessageConverters(final List<HttpMessageConverter<?>> converters) {
		converters.add(mappingJackson2HttpMessageConverter());
		addDefaultHttpMessageConverters(converters);
	}

	@Bean
	public StringHttpMessageConverter stringConverter() {
		final StringHttpMessageConverter converter = new StringHttpMessageConverter();
		converter.setDefaultCharset(Charset.forName("UTF-8"));
		// MediaType mediaType = new MediaType("text/plain;charset=UTF-8");
		final List<MediaType> types = new ArrayList<>();
		// types.add(mediaType);
		types.add(MediaType.TEXT_PLAIN);
		converter.setSupportedMediaTypes(types);
		return converter;
	}

	/**
	 * 设置跨域 //addMapping("/api/*")
	 */
	@Override
	public void addCorsMappings(final CorsRegistry registry) {
		registry.addMapping("/*").allowedOrigins("*");
	}

	@Bean
	LoginInterceptor loginInterceptor() {
		return new LoginInterceptor();
	}

	/*
	 * <!-- 异常处理器 --> <bean id="exceptionResolver"
	 * class="web.core.CP_SimpleMappingExceptionResolver"> <property
	 * name="defaultErrorView" value="common_error" /> <property
	 * name="exceptionAttribute" value="exception" /> <property
	 * name="exceptionMappings"> <props> <prop
	 * key="java.lang.RuntimeException">common_error</prop> </props> </property>
	 * </bean>
	 */
	@Override
	protected void addInterceptors(final InterceptorRegistry registry) {
		// TODO Auto-generated method stub
		// registry.addInterceptor(new ControllerLogInterceptor());
//		final HandlerInterceptor loginInterceptor = new LoginInterceptor();
//		registry.addInterceptor(loginInterceptor);
//		registry.addInterceptor(sessionInterceptor).addPathPatterns("/**");
//		System.out.println("注入拦截器");
//		super.addInterceptors(registry);

		registry.addInterceptor(loginInterceptor()).addPathPatterns("/**");
		System.out.println("注入拦截器");
		super.addInterceptors(registry);
	}

	/**
	 * 静态资源处理器 ，用于注册静态资源不被拦截
	 */
//	 @Override
//	 protected void addResourceHandlers(ResourceHandlerRegistry registry) {
//	 registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
//
//	 registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
//	 }
	@Bean
	public Docket buildDocket() {
		System.err.println("加载swagger配置");
		return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()//
				.apis(RequestHandlerSelectors.basePackage("com.hyst"))// controller路径
				.paths(PathSelectors.any()).build();
	}

	/*
	 * "标题 title", "描述 description", "termsOfServiceUrl", "联系邮箱 contact email",
	 * "许可证的类型 license type", "许可证的链接 license url"
	 */
	private ApiInfo apiInfo() {
		return new ApiInfoBuilder().title("预算管理系统API说明文档").description("预算管理系统--数据支撑系统")
				.contact(new Contact("HYST", "地址", "电子邮件")).build();

	}

	@Override
	public void addViewControllers(final ViewControllerRegistry registry) {
		registry.addViewController("/").setViewName("/index.html");
		registry.addViewController("/login").setViewName("/login.html");
	}

	/**
	 * @Description: 文件上传
	 * @return CommonsMultipartResolver
	 */
	@Bean
	public MultipartResolver multipartResolver() {
		final CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
		// 设置上传文件的大小限制
		multipartResolver.setMaxUploadSize(1204 * 1024 * 20);
		// 设置文件默认编码
		multipartResolver.setDefaultEncoding("UTF-8");
		return multipartResolver;
	}
}
